import 'package:flutter/material.dart';
import './client_dio.dart';
import './pack_screens.dart';
import 'dart:convert';

class PacksHome extends StatefulWidget {
  @override
  State createState() => new PacksHomeState();
}

class PacksHomeState extends State<PacksHome> {
  var start = 0;
  var limit = 10;
  var total = 0;
  var res;
  var query = "";
  var rows = [
    TableRow(
      decoration: BoxDecoration(color: Colors.grey[200]),
      children: [
        Text("id"),
        Text("名称"),
        Text("创建时间"),
        Text("操作"),
      ]
    )
  ];
  
  final TextEditingController at_Controller = new TextEditingController(text: "1");
  TextEditingController search_Controller = new TextEditingController();

  @override
  void initState() {
    super.initState();
    start = 0;
    query = "";
    load_data();
  }

  void load_data() {
    packs({
      "limit": limit,
      'start': start,
      'search': query
    }, (r) {
      res = r;
      print(res);
      total = res["total"];
      var newRows = <TableRow>[];
      newRows.add(TableRow(
        decoration: BoxDecoration(
          color: Colors.blue.shade50,
          border: Border(bottom: BorderSide(width: 2.0, color: Colors.blue.shade300)),
        ),
        children: [
          Padding(
            padding: EdgeInsets.symmetric(vertical: 12.0, horizontal: 8.0),
            child: Text(
              "ID",
              style: TextStyle(fontWeight: FontWeight.bold, fontSize: 14.0, color: Colors.blue.shade900),
            ),
          ),
          Padding(
            padding: EdgeInsets.symmetric(vertical: 12.0, horizontal: 8.0),
            child: Text(
              "名称",
              style: TextStyle(fontWeight: FontWeight.bold, fontSize: 14.0, color: Colors.blue.shade900),
            ),
          ),
          Padding(
            padding: EdgeInsets.symmetric(vertical: 12.0, horizontal: 8.0),
            child: Text(
              "创建时间",
              style: TextStyle(fontWeight: FontWeight.bold, fontSize: 14.0, color: Colors.blue.shade900),
            ),
          ),
          Padding(
            padding: EdgeInsets.symmetric(vertical: 12.0, horizontal: 8.0),
            child: Text(
              "操作",
              style: TextStyle(fontWeight: FontWeight.bold, fontSize: 14.0, color: Colors.blue.shade900),
            ),
          ),
        ]
      ));
      
      for (var i = 0; i < res["data"].length; i++) {
        bool isEven = i % 2 == 0;
        newRows.add(TableRow(
          decoration: BoxDecoration(
            color: isEven ? Colors.white : Colors.grey.shade50,
          ),
          children: ([
            Padding(
              padding: EdgeInsets.symmetric(vertical: 10.0, horizontal: 8.0),
              child: Text(res["data"][i]["id"].toString(), style: TextStyle(fontSize: 13.0)),
            ),
            Padding(
              padding: EdgeInsets.symmetric(vertical: 10.0, horizontal: 8.0),
              child: Text(res["data"][i]["name"] == null ? "" : res["data"][i]["name"], style: TextStyle(fontSize: 13.0)),
            ),
            Padding(
              padding: EdgeInsets.symmetric(vertical: 10.0, horizontal: 8.0),
              child: Text(res["data"][i]["create_time"] == null ? "" : res["data"][i]["create_time"], style: TextStyle(fontSize: 13.0)),
            ),
            Padding(
              padding: EdgeInsets.symmetric(vertical: 10.0, horizontal: 8.0),
              child: Row(
                mainAxisAlignment: MainAxisAlignment.spaceAround,
                children: [
                  ElevatedButton.icon(
                    onPressed: () { doEdit2(i); },
                    icon: Icon(Icons.edit, size: 14.0),
                    label: Text("编辑", style: TextStyle(fontSize: 12.0)),
                    style: ElevatedButton.styleFrom(
                      backgroundColor: Colors.blue.shade400,
                      foregroundColor: Colors.white,
                      padding: EdgeInsets.symmetric(horizontal: 12.0, vertical: 6.0),
                      minimumSize: Size(80, 36),
                    ),
                  ),
                  ElevatedButton.icon(
                    onPressed: () { doDelete(i); },
                    icon: Icon(Icons.delete, size: 14.0),
                    label: Text("删除", style: TextStyle(fontSize: 12.0)),
                    style: ElevatedButton.styleFrom(
                      backgroundColor: Colors.red.shade400,
                      foregroundColor: Colors.white,
                      padding: EdgeInsets.symmetric(horizontal: 12.0, vertical: 6.0),
                      minimumSize: Size(80, 36),
                    ),
                  ),
                ]
              ),
            ),
          ]),
        ));
      }
      
      setState(() {
        rows = newRows;
      });
    }, err_treat);
  }

  void err_treat(e) {
    print("Error: $e");
  }

  void doPrev() {
    if (res == null) return;
    start -= limit;
    if (start < 0) start = 0;
    load_data();
  }

  void doGo() {
    if (res == null) return;
    start = int.parse(at_Controller.text);
    if (start < 0) start = 0;
    load_data(); 
  }

  void do_new() async {
    bool? result = await Navigator.push(
      context,
      MaterialPageRoute(builder: (context) => CreatePackScreen()),
    );
    if (result == true) {
      load_data(); // Reload data to show the new pack
    }
  }

  void doDelete(i) async {
    showDialog(context: context, builder: (BuildContext context) {
      return Dialog(
        child: Container(
          height: 300,
          child: Column(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              FlutterLogo(size: 150),
              Text(res["data"][i]["name"] ?? "", style: TextStyle(fontSize: 20)),
              ElevatedButton(
                onPressed: () {
                  packDelete({"id": res["data"][i]["id"]}, (r) {
                    print(r);
                    load_data();
                  }, (e) {
                    print(e);
                  });
                  Navigator.of(context).pop();
                },
                child: Text("Ok"),
              ),
              ElevatedButton(
                onPressed: () {
                  Navigator.of(context).pop();
                },
                child: Text("Cancel"),
              ),
            ],
          ),
        ),
      );
    });
  }

  void doEdit2(i) async {
    bool? result = await Navigator.push(
      context,
      MaterialPageRoute(
        builder: (context) => PackArgumentsScreen(),
        settings: RouteSettings(
          arguments: PackArguments(res["data"][i]["id"], res["data"][i]["name"]),
        ),
      ),
    );
    if (result == true) {
      load_data(); // Reload data to show the updated pack
    }
  }

  void do_search() {
    start = 0;
    query = search_Controller.text;
    load_data();
  }

  void doNext() {
    if (res == null) return;
    start += limit;
    if (start > res["total"] - limit) start = res["total"] - limit;
    if (start < 0) start = 0;
    load_data();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('包'),
      ),
      body: Container(
        padding: EdgeInsets.all(20.0),
        child: SingleChildScrollView(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.start,
            children: <Widget>[
              Container(
                margin: EdgeInsets.only(bottom: 20.0),
                padding: EdgeInsets.all(12.0),
                decoration: BoxDecoration(
                  color: Colors.white,
                  borderRadius: BorderRadius.circular(8.0),
                  boxShadow: [
                    BoxShadow(
                      color: Colors.grey.withOpacity(0.1),
                      spreadRadius: 1,
                      blurRadius: 3,
                      offset: Offset(0, 2),
                    ),
                  ],
                ),
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: <Widget>[
                    Expanded(
                      child: TextField(
                        controller: search_Controller,
                        decoration: InputDecoration(
                          labelText: "名称搜索",
                          border: OutlineInputBorder(),
                          prefixIcon: Icon(Icons.search),
                          contentPadding: EdgeInsets.symmetric(horizontal: 16.0, vertical: 12.0),
                        ),
                      ),
                    ),
                    SizedBox(width: 12.0),
                    ElevatedButton.icon(
                      icon: Icon(Icons.search),
                      label: Text("搜索"),
                      onPressed: do_search,
                      style: ElevatedButton.styleFrom(
                        backgroundColor: Colors.grey.shade700,
                        foregroundColor: Colors.white,
                      ),
                    ),
                    SizedBox(width: 12.0),
                    ElevatedButton.icon(
                      icon: Icon(Icons.add),
                      label: Text("新建"),
                      onPressed: do_new,
                      style: ElevatedButton.styleFrom(
                        backgroundColor: Colors.green.shade600,
                        foregroundColor: Colors.white,
                      ),
                    ),
                  ],
                ),
              ),
              SingleChildScrollView(
                scrollDirection: Axis.horizontal,
                child: Container(
                  margin: EdgeInsets.only(top: 20.0),
                  decoration: BoxDecoration(
                    borderRadius: BorderRadius.circular(8.0),
                    border: Border.all(color: Colors.blue.shade200, width: 1.0),
                    boxShadow: [
                      BoxShadow(
                        color: Colors.grey.withOpacity(0.1),
                        spreadRadius: 1,
                        blurRadius: 3,
                        offset: Offset(0, 2),
                      ),
                    ],
                  ),
                  child: ClipRRect(
                    borderRadius: BorderRadius.circular(8.0),
                    child: Table(
                      border: TableBorder(
                        horizontalInside: BorderSide(color: Colors.grey.shade200, width: 1.0),
                      ),
                      defaultVerticalAlignment: TableCellVerticalAlignment.middle,
                      columnWidths: const <int, TableColumnWidth>{
                        0: FixedColumnWidth(80),  // id
                        1: FixedColumnWidth(160), // name
                        2: FixedColumnWidth(160), // create_time
                        3: FixedColumnWidth(200), // actions
                      },
                      children: rows,
                    ),
                  ),
                ),
              ),
              SizedBox(height: 20.0),
              Row(
                mainAxisAlignment: MainAxisAlignment.center,
                children: <Widget>[
                  SizedBox(
                    width: 150,
                    child: TextField(
                      controller: at_Controller,
                      decoration: InputDecoration(labelText: "页码"),
                    ),
                  ),
                  SizedBox(width: 16.0),
                  ElevatedButton(
                    onPressed: doGo,
                    style: ElevatedButton.styleFrom(
                      backgroundColor: Colors.green.shade600,
                      foregroundColor: Colors.white,
                      minimumSize: Size(80, 45),
                      shape: RoundedRectangleBorder(
                        borderRadius: BorderRadius.circular(12),
                      ),
                      elevation: 4,
                      textStyle: TextStyle(fontSize: 15, fontWeight: FontWeight.w500),
                    ),
                    child: Text("Go"),
                  ),
                  SizedBox(width: 12.0),
                  ElevatedButton(
                    onPressed: doPrev,
                    style: ElevatedButton.styleFrom(
                      backgroundColor: Colors.green.shade600,
                      foregroundColor: Colors.white,
                      minimumSize: Size(80, 45),
                      shape: RoundedRectangleBorder(
                        borderRadius: BorderRadius.circular(12),
                      ),
                      elevation: 4,
                      textStyle: TextStyle(fontSize: 15, fontWeight: FontWeight.w500),
                    ),
                    child: Text("Prev"),
                  ),
                    SizedBox(width: 16.0),
                  Text(
                    "${start.toString()}/${total.toString()}",
                    style: TextStyle(
                      fontSize: 16,
                      fontWeight: FontWeight.bold,
                      color: Colors.grey.shade700,
                    ),
                  ),
                  SizedBox(width: 16.0),
                  ElevatedButton(
                    onPressed: doNext,
                    style: ElevatedButton.styleFrom(
                      backgroundColor: Colors.green.shade600,
                      foregroundColor: Colors.white,
                      minimumSize: Size(80, 45),
                      shape: RoundedRectangleBorder(
                        borderRadius: BorderRadius.circular(12),
                      ),
                      elevation: 4,
                      textStyle: TextStyle(fontSize: 15, fontWeight: FontWeight.w500),
                    ),
                    child: Text("Next"),
                  ),
                ],
              )
            ],
          ),
        ),
      ),
    );
  }
}